'use client';

import React from 'react';

export interface CommandItem {
  id: string;
  label: string;
  shortcut?: string;
  action: () => void | Promise<unknown>;
}

interface Props {
  commands: CommandItem[];
  open: boolean;
  onClose: () => void;
}

export function CommandPalette({ commands, open, onClose }: Props) {
  const [query, setQuery] = React.useState('');
  const inputRef = React.useRef<HTMLInputElement | null>(null);

  React.useEffect(() => {
    if (open) {
      const handler = (event: KeyboardEvent) => {
        if (event.key === 'Escape') {
          onClose();
        }
      };
      window.addEventListener('keydown', handler);
      setTimeout(() => inputRef.current?.focus(), 16);
      return () => window.removeEventListener('keydown', handler);
    } else {
      setQuery('');
    }
  }, [open, onClose]);

  if (!open) return null;

  const filtered = commands.filter(cmd => cmd.label.toLowerCase().includes(query.toLowerCase()));

  return (
    <div className="palette">
      <div className="palette-dialog">
        <input
          ref={inputRef}
          placeholder="Type a command"
          value={query}
          onChange={event => setQuery(event.target.value)}
        />
        <ul>
          {filtered.map(command => (
            <li key={command.id}>
              <button
                onClick={() => {
                  const maybe = command.action();
                  if (maybe instanceof Promise) {
                    maybe.finally(onClose);
                  } else {
                    onClose();
                  }
                }}
              >
                <span>{command.label}</span>
                {command.shortcut && <kbd>{command.shortcut}</kbd>}
              </button>
            </li>
          ))}
          {filtered.length === 0 && <li className="muted">No matching commands.</li>}
        </ul>
      </div>
    </div>
  );
}
